<template>
  <div>
    <button @click="startRecognition">开始识别</button>
    <button @click="stopRecognition">停止识别</button>
    <p>识别结果: {{ transcript }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      recognition: null,
      transcript: "", // 用于存储最终结果
      interimTranscript: "", // 用于存储临时结果
    };
  },
  methods: {
    startRecognition() {
      if (!("webkitSpeechRecognition" in window)) {
        alert("您的浏览器不支持语音识别，请使用 Chrome 浏览器。");
        return;
      }

      this.recognition = new webkitSpeechRecognition();
      this.recognition.continuous = true; // 设置为连续识别
      this.recognition.interimResults = true; // 返回临时结果
      this.recognition.lang = "zh-CN"; // 设置语言为中文

      this.recognition.onstart = () => {
        console.log("语音识别已启动");
      };

      this.recognition.onresult = (event) => {
        let finalTranscript = ""; // 用于存储最终结果
        this.interimTranscript = ""; // 清空临时结果

        for (let i = event.resultIndex; i < event.results.length; ++i) {
          if (event.results[i].isFinal) {
            // 如果是最终结果，追加到 finalTranscript
            finalTranscript += event.results[i][0].transcript;
          } else {
            // 如果是临时结果，存储到 interimTranscript
            this.interimTranscript += event.results[i][0].transcript;
          }
        }

        // 将最终结果追加到 transcript 中
        this.transcript += finalTranscript;

        // 实时显示临时结果（可选）
        console.log("临时结果:", this.interimTranscript);
      };

      this.recognition.onerror = (event) => {
        console.error("语音识别错误", event);
      };

      this.recognition.onend = () => {
        console.log("语音识别服务已断开");
      };

      this.recognition.start();
    },
    stopRecognition() {
      if (this.recognition) {
        this.recognition.stop();
      }
    },
  },
};
</script>

<style scoped>
button {
  margin: 5px;
}
</style>
